package net.studou.dao;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class CommonDao {
	// 声明一个class
	@SuppressWarnings("unchecked")
	protected Class clazz;

	@Resource(name = "hibernateTemplate")
	private HibernateTemplate hibernateTemplate;

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	// 添加
	public void save(Object obj) {
		try {
			hibernateTemplate.save(obj);
		} catch (RuntimeException e) {
			throw e;
		}
	}

	// 删除
	public void delete(Object obj) {
		try {
			hibernateTemplate.delete(obj);
		} catch (RuntimeException e) {
			throw e;
		}
	}

	// 根据id 查找
	public Object findById(Serializable id) {
		Object obj = null;
		try {
			obj = hibernateTemplate.get(clazz, id);
		} catch (RuntimeException e) {
			throw e;
		}
		return obj;
	}

	// 根据实例查找
	@SuppressWarnings("unchecked")
	public List findByExample(String[] props, Object[] vs) {
		List list = null;
		try {
			String hql = "from " + clazz.getName() + " a where 1=1";
			for (int i = 0; i < props.length; i++) {
				hql = hql + " and a." + props[i] + "=" + vs[i];
			}
			list = hibernateTemplate.find(hql);
			;
		} catch (RuntimeException e) {
			throw e;
		}
		return list;
	}

	// 根据其中一个属性查找
	@SuppressWarnings("unchecked")
	public List findByProperty(String propertyName, Object value) {
		List list = null;
		try {
			String hql = "from " + clazz.getName() + " a where a." + propertyName + " = ?";
			list = hibernateTemplate.find(hql, value);
		} catch (RuntimeException e) {
			throw e;
		}
		return list;
	}

	// 查找所有的记录
	@SuppressWarnings("unchecked")
	public List findAll() {
		List list = null;
		try {
			String hql = "from " + clazz.getName();
			list = hibernateTemplate.find(hql);
		} catch (RuntimeException e) {
			throw e;
		}
		return list;
	}

	// 修改
	public void update(Object obj) {
		try {
			hibernateTemplate.update(obj);
		} catch (RuntimeException e) {
			throw e;
		}
	}
}
